package com.swak.fx.support.ui.html;

import java.io.File;
import java.net.URI;
import java.util.Iterator;
import java.util.List;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.nodes.Node;
import org.jsoup.select.Elements;

import com.swak.fx.support.ui.UIImage.ImageCache;
import com.swak.utils.ImageUtils;
import com.swak.utils.Lists;
import com.swak.utils.StringUtils;

/**
 * 解析 Html
 * 
 * @author 618lf
 */
public class HtmlParser {

	/**
	 * 只保留第一层
	 * 
	 * @param html
	 * @return
	 */
	public static String parse(String html) {

		// load doc
		Document htmlDoc = Jsoup.parse(html);

		// 文档
		List<String> ps = Lists.newArrayList();

		// 第一层
		Iterator<Node> nodes = htmlDoc.body().childNodes().iterator();
		while (nodes.hasNext()) {
			Node node = nodes.next();
			if (node instanceof Element) {
				Element element = (Element) node;
				Elements images = element.getElementsByTag("img");
				if (!images.isEmpty()) {
					for (Element image : images) {
						String tempSrc = image.attr("src");
						ps.add(StringUtils.format("<p><img src=\"%s\"></p>", parseImage(tempSrc)));
					}
					continue;
				}
				String text = element.text();
				if (StringUtils.isNotBlank(text)) {
					ps.add(StringUtils.format("<p>%s</p>", text));
				}
			}
		}

		// 解析Html
		parseImages(htmlDoc);

		// 返回解析后的html
		return StringUtils.join(ps, "");
	}

	private static void parseImages(Document htmlDoc) {
		Elements images = htmlDoc.getElementsByTag("img"); // 获取所有的image，转码。
		Iterator<Element> it = images.iterator();
		while (it.hasNext()) {
			Element image = it.next();
			Element parent = image.parent();
			String tempSrc = image.attr("src");
			image.attr("src", parseImage(tempSrc));
			parent.empty();
			parent.append(image.outerHtml());
		}
	}

	private static String parseImage(String image) {
		if (StringUtils.startsWith(image, "file:")) {
			return parseImageWithFileProtocol(image);
		}
		if (StringUtils.startsWith(image, "http:")) {
			return parseImageWithHttpProtocol(image);
		}
		if (StringUtils.startsWith(image, "https:")) {
			return parseImageWithHttpProtocol(image);
		}
		return StringUtils.EMPTY;
	}

	private static String parseImageWithFileProtocol(String image) {
		File imageFile = new File(URI.create(image));
		return "data:image/png;base64," + ImageUtils.toBase64(imageFile);
	}

	private static String parseImageWithHttpProtocol(String image) {
		ImageCache cache = new ImageCache(image).start();
		try {
			cache.successProperty().get();
			return "data:image/png;base64," + ImageUtils.toBase64(cache.openStream());
		} catch (Exception e) {
		} finally {
			cache.clear();
		}
		return StringUtils.EMPTY;
	}
}
